/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * author Svetlana Shikhutskaya
 */

var roles="";
var totalNumber=1;
var pageNumber=1;
var count;
var prevCount=0;
var oldName;
var idGroup;

//hide editing block
$(function(){
    $(document).on('submit','#minimize',function(e){
        e.preventDefault();
        hideBlock();
    })
})

//handles the event 'onsubmit' on form '.js-creategroup' and show Create block
$(function(){
    $(document).on('submit', '.js-creategroup', function(e){
        e.preventDefault();
        showBlock();
        hideEditBtn();
        showCreateBtn();
        clearBlock();
        document.getElementById('warningGrName').innerHTML = 'Enter the name';
    })
})

//handles the event 'onsubmit' on form '.js-editgroup' and show Edit block if at least one group is selected
$(function(){
    $(document).on('submit', '.js-editgroup', function(e){
        e.preventDefault();
        hideBlock();
        document.getElementById('warningGrName').innerHTML = '';
        checkGroupsForEdit();
    })
})

function init(){
    pageNumber=parseInt(document.getElementById("pageNumber").value);
    loadGroups();
    document.getElementById("num").innerHTML=pageNumber;
}

function countPages(){
    var number='1';
    var n=document.getElementById("page-count").value;
    $.post('CountRecords', {
        record: "group",
        num: n
    }, function(result){
        if(result!="0"){
            number=result;
        }
        totalNumber=number;
        document.getElementById("total-num").innerHTML=number;
    })
}

function hideCreateBtn(){
    //    alert('hideCreateBtn');
    document.getElementById("create").style.display='none';
    document.getElementById("groupNameCreate").style.display='none';
//    alert('finish');
}
function showCreateBtn(){
    //    alert('showCreateBtn');
    document.getElementById("create").style.display='block';
    document.getElementById("groupNameCreate").style.display='block';
//    alert('finish');
}

function hideEditBtn(){
    //    alert('hideEditBtn');
    document.getElementById("edit").style.display='none';
    document.getElementById("groupNameEdit").style.display='none';
//    alert('finish');
}
function showEditBtn(){
    //    alert('showEditBtn');
    document.getElementById("edit").style.display='block';
    document.getElementById("groupNameEdit").style.display='block';
//    alert('finish');
}

function hideBlock(){
    //    alert('hideBlock');
    document.getElementById("block").style.display="none";
//    alert('finish');
}
function showBlock(){
    //    alert('showBlock');
    document.getElementById("block").style.display="block";
//    alert('finish');
}

//clear the data of each block between their switching
function clearBlock(){
    document.getElementById("groupNameCreate").value='';
    document.getElementById("groupNameEdit").value='';
    document.getElementById("Admin").checked=false;
    document.getElementById("Warehouse_Employee").checked=false;
    document.getElementById("Courier").checked=false;
    document.getElementById("Customer").checked=false;
    document.getElementById('create').disabled=true;
}

//make a double check and call function witch create a new group
$(function(){
    $(document).on('click','#create',function(e){
        e.preventDefault();
        roles=fillRoles(roles);
        //        alert(roles);
        if(roles!=""){
            addGroup();
        }
        else {
            document.getElementById('warning').innerHTML = 'At least one role must be selected';
        }
    })
})

//check how many groups is checked on the page
function checkGroupsForEdit(){
    var number;
    var j=0;
    var n=count;
    if(count==0){
        n=prevCount;
    }
    for (var i=0;i<n;i++){
        if($('#check-'+i).prop("checked")){
            j++;
            number=i;
        }
    }
    if(j==1){
        showBlock();
        hideCreateBtn();
        showEditBtn();
        clearBlock();
        getGroup(number);
        document.getElementById("edit").disabled=false;
    }
}

//return group by id in editing
function getGroup(number){
    var groupName=document.getElementById('name-'+number).innerHTML;
    oldName=groupName;
    //    console.log(oldName);
    $.post('FindGroup',{
        groupName:groupName
    },function(result){
        if(result!=''){
            var group=$.parseJSON(result);
            idGroup=group.id;
            document.getElementById("groupNameEdit").value=group.name;
            for (var i=0;i<group.roles.length;i++){
                if(group.roles[i]=='Warehouse Employee'){
                    document.getElementById('Warehouse_Employee').checked=true;
                }
                else{
                    if(group.roles[i]=='Administrator'){
                        document.getElementById('Admin').checked=true;
                    }
                    else{
                        document.getElementById(group.roles[i]).checked=true;
                    }
                }
            }
        }
    })
}

//edit group
$(function(){
    $(document).on('click','#edit',function(e){
        e.preventDefault();
        roles=fillRoles(roles);
        if(roles!=""){
            $.post('EditGroup',
            {
                oldName:oldName,
                groupName:document.getElementById("groupNameEdit").value,
                roles:roles
            },function(result){
                window.location.reload();
            })
        }
    })
})

//check Group
//Name oninput
function checkCreateGroupName(){
    name=document.getElementById("groupNameCreate").value;
    if(name!=''){
        if(validateGroupName(name)){
            if(name.length>=4){
                document.getElementById('warningGrName').innerHTML = '';
                $.post("CheckGroupName",{
                    groupName:name
                }, function(result){
                    if(result=="true"){
                        document.getElementById('warningGrName').innerHTML = '';
                        document.getElementById('create').disabled=false;
                    }
                    else{
                        document.getElementById('warningGrName').innerHTML = 'Such group is already exists';
                        document.getElementById('create').disabled=true;
                    }
                })
            }
            else{
                document.getElementById('warningGrName').innerHTML = 'Too short name';
                document.getElementById('create').disabled=true;
            }
        }
        else{
            document.getElementById('warningGrName').innerHTML = 'You can use only letters (a-z), numbers and underscore characters';
            document.getElementById('create').disabled=true;
        }
    }
    else{
        document.getElementById('warningGrName').innerHTML = 'Enter the name';
        document.getElementById('create').disabled=true;
    }
}

function checkEditGroupName(){
    name=document.getElementById("groupNameEdit").value;
    if(name.length>0){
        if(validateGroupName(name)){
            if(name.length>=4){
                document.getElementById('warningGrName').innerHTML = '';
                $.post("CheckGroupName",{
                    groupName:name
                }, function(result){
                    //                    console.log(result);
                    //                    console.log(idGroup);
                    //                    console.log(result==idGroup);
                    if(result==idGroup){
                        document.getElementById('warningGrName').innerHTML = '';
                        document.getElementById('edit').disabled=false;
                    } else{
                        if(result=='true'){
                            document.getElementById('warningGrName').innerHTML = '';
                            document.getElementById('edit').disabled=false;
                        }
                        else{
                            document.getElementById('warningGrName').innerHTML = 'Such group is already exists';
                            document.getElementById('edit').disabled=true;
                        }
                    }
                })
            }
            else{
                document.getElementById('warningGrName').innerHTML = 'Too short name';
                document.getElementById('edit').disabled=true;
            }
        }
        else{
            document.getElementById('warningGrName').innerHTML = 'You can use only letters (a-z), numbers and underscore characters';
            document.getElementById('edit').disabled=true;
        }
    }
    else{
        document.getElementById('warningGrName').innerHTML = 'Enter the name';
        document.getElementById('edit').disabled=true;
    }
}

function validateGroupName(str){
    var regex=new RegExp("^[0-9a-zA-Z_\\s]+$");
    return regex.test(str);
}

function addGroup(){
    $.post("AddGroup",
    {
        groupName:document.getElementById("groupNameCreate").value,
        Roles:roles
    },
    function(result){
        window.location.reload();
    })
}

function loadGroups(){
    pageCount=document.getElementById("page-count").value;
    $.post('LoadGroup',{
        pageNumber:pageNumber,
        pageCount:pageCount
    },function(result){
        var groups=$.parseJSON(result);
        if(count>0){
            prevCount=count;
        }
        count=groups.length;
        if(count>0){
            DeleteRows();
            DisplayGroups(groups);
        }
        else {
            pageNumber--;
        }
        document.getElementById("num").innerHTML=pageNumber;
    })
    countPages();
}

//go to the previous page
$(function(){
    $(document).on('submit','.js-left-page',function(e){
        e.preventDefault();
        if(pageNumber!=1){
            pageNumber--;
            loadGroups();
        }
    })
})

//go to the next page
$(function(){
    $(document).on('submit','.js-right-page',function(e){
        e.preventDefault();
        pageNumber++;
        if(pageNumber<=totalNumber){
            loadGroups();
        } else{
            pageNumber--;
        }
    })
})

//fill content for table and generate table rows and columns
function DisplayGroups(groups){
    //    console.log(groups);
    for (var i=0;i<groups.length;i++){
        $('.group-table').append('<tr id=row-'+i+'></tr>');
        $('.group-table > tbody > tr:last').append('<td class="check"><input name="name" value="'+groups[i]["id"]+'" id="check-'+i+'" type="checkbox"></td>');
        $('.group-table > tbody > tr:last').append('<td class="str"><span id="name-'+i+'">'+groups[i]["name"]+'</span></td>');
        $('.group-table > tbody > tr:last').append('<td class="str" id="str">'+groups[i]["roles"]+'</td>');
    }
}

function DeleteRows(){
    //    alert(prevCount+"DelRow");
    for (var i=0;i<prevCount;i++){
        //        alert(i);
        $('#row-'+i).remove();
    }
}

//delete group
$(function(){
    $(document).on('submit','.js-deletegroup',function(e){
        e.preventDefault();
        var j=0;
        var k=0;
        var n=count;
        if(count==0){
            n=prevCount;
        }
        var line='';
        for (var i=0;i<n;i++){
            if($('#check-'+i).prop("checked")){
                if(k>0){
                    line+=','+document.getElementById("name-"+i).innerHTML;
                }
                else{
                    line+=document.getElementById("name-"+i).innerHTML;
                    k++;
                }
                j++;
            }
        }
        if(j>0){
            document.getElementById("warningDelete").innerHTML='';
            DeleteGroups(line);
        }
        else {
            document.getElementById("warningDelete").innerHTML='No groups is checked';
        }
    })
})

function DeleteGroups(line){
    $.post('DeleteGroup', {
        groups:line
    }, function(result){
        window.location.reload();
    })
}

$(function(){
    $(document).on('submit','.js-back-page',function(e){
        e.preventDefault();
        window.location.href='userview';
    })
})

$(function(){
    $(document).on('submit','.js-jump-page',function(e){
        e.preventDefault();
        pageNumber=document.getElementById("jump-page").value;
        loadGroups();
    })
})

function validateJumpPage(){
    var regex=new RegExp("^[0-9]+$");
    var str=document.getElementById("jump-page").value;
    document.getElementById("jump-warning").innerHTML="";
    if(str.length>0){
        if(regex.test(str)){
            str=parseInt(str);
            if(str!=0 && str<=totalNumber){
                document.getElementById("jump-warning").innerHTML="";
                document.getElementById("jump-btn").disabled=false;
            }else{
                document.getElementById("jump-warning").innerHTML="Such page doesn't exist";
                document.getElementById("jump-btn").disabled=true;
            }
        } else {
            document.getElementById("jump-warning").innerHTML="You can enter only numbers";
            document.getElementById("jump-btn").disabled=true;
        }
    } else {
        document.getElementById("jump-warning").innerHTML="";
    }
}